import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:get/get.dart';
import 'package:volume_controller/volume_controller.dart';
import 'package:zz_listen_english/common/api/plan/plan.dart';
import 'package:zz_listen_english/common/models/plan/plan_study_model.dart';
import 'package:zz_listen_english/common/utils/audio_play_manager.dart';
import '../../common/api/http_head.dart';
import '../../common/utils/bottom_sheet.dart';
import '../../common/utils/storage.dart';

class AudioPlayController extends GetxController with WidgetsBindingObserver {
  AudioPlayController();

  late String studyPlanName = "请选择学习计划";
  List<PlanStudyModel> audioUrlList = [];
  final player = AudioPlayerManager();

  _initData() async {
    ambiguate(WidgetsBinding.instance)!.addObserver(this);
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.black,
    ));
    await getAudioPlayList();
    studyPlanName = Storage().getString("studyPlanName") == ""
        ? "请选择学习计划"
        : Storage().getString("studyPlanName");
    update(["audio_play"]);
  }

  //
  // Future<void> seek(Duration position) async {
  //   await player.seek(position);
  // }

  playAudio(int index, PlanStudyModel planStudyModel) {
    player.playSort();
    player.seek(index);
    update(["audio_play"]);
  }

//随机播放
  shufflePlayModel() {
    player.playShufftle();
  }

//停止
  audioStop() {
    player.stop();
  }

//顺序播放
  orderPlayModel() {
    player.playSort();
  }

  getAudioPlayList() {
    String studyPlanId = Storage().getString("studyPlanId");
    if (studyPlanId == "" || studyPlanId == null) {
      return;
    }
    PlanApi.getPlStudyPlanVideoListApi(
            {"status": 1, "studyPlanId": studyPlanId, "playType": 1})
        .then((res) {
      if (res['code'] == "00000") {
        List<dynamic> audioList = res['data'];
        audioUrlList.clear();
        player.setAudioUrls([]);
        List<String> urlList = [];
        if (!audioList.isEmpty) {
          for (int i = 0; i < audioList.length; i++) {
            var vo = audioList[i];
            String audio = HttpHead.minioUrl() + "/" + vo["audioUrl"];
            PlanStudyModel planStudyModel = PlanStudyModel.fromJson(vo);
            planStudyModel.indexNum = i;
            planStudyModel.audioUrl = audio;
            audioUrlList.add(planStudyModel);
            urlList.add(audio);
          }
          player.setAudioUrls(urlList);
        }
        update(["audio_play"]);
      }
      ;
    });
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  showPicker() async {
    final List<PickerItem> sysCertificateTypeList = [];
    PlanApi.getMyStudyPlanListApi({'type': "1"}).then((res) {
      if (res['code'] == "00000") {
        List<dynamic> certificateTypeList = res['data'];
        for (var itemVo in certificateTypeList) {
          PickerItem keyValueModel =
              PickerItem(text: Text(itemVo["name"]), value: itemVo["id"]);
          sysCertificateTypeList.add(keyValueModel);
        }
        ActionBottomSheet.data(
          title: '学习计划',
          context: Get.context!,

          // 数据
          adapter: PickerDataAdapter(data: sysCertificateTypeList),
          // 确认回调
          onConfirm: (value) {
            if (value.isEmpty) return;
            String studyPlanNameTitle = "";
            for (var itemVo in certificateTypeList) {
              String id = itemVo["id"].toString();
              if (id == value[0].toString()) {
                studyPlanNameTitle = itemVo['name'].toString();
              }
            }
            ;
            Storage().setString("studyPlanId", value[0].toString());
            Storage().setString("studyPlanName", studyPlanNameTitle);
            studyPlanName = studyPlanNameTitle;
            getAudioPlayList();
          },
        );
      }
    });
  }

  @override
  void onClose() {
    ambiguate(WidgetsBinding.instance)!.removeObserver(this);
    super.onClose();
  }
}
